package com.whereareyou.servlet;

import com.google.gson.Gson;
import com.google.inject.Provider;
import com.whereareyou.model.Relationship;
import com.whereareyou.model.User;
import com.whereareyou.service.RelationshipService;
import com.whereareyou.service.UserService;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 家玮 on 2014/7/27.
 */
@Singleton
public class RelationshipServlet extends HttpServlet{
    private final RelationshipService relationshipService;
    private final UserService userService;
    @Inject
    public RelationshipServlet(Provider<RelationshipService> relationshipServicePder,Provider<UserService> userServiceProvider) {
        this.relationshipService = relationshipServicePder.get();
        this.userService = userServiceProvider.get();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryUserId = req.getParameter("userId");
        List<Relationship> relationshipList = relationshipService.findAllByUserId(queryUserId);
        List<Map<String,String>> friends = new ArrayList<Map<String,String>>();
        relationshipList.forEach((relationship)->{
            Map<String,String> map = new HashMap<String, String>();
            if(!relationship.getUser1().equals(queryUserId)){
                User user = userService.getByUserId(relationship.getUser1());
                map.put("id",relationship.getUser1());
                map.put("nickname",relationship.getUser1Nickname());
                map.put("photo",user.getPhoto());
            }else{
                User user = userService.getByUserId(relationship.getUser2());
                map.put("id",relationship.getUser2());
                map.put("nickname",relationship.getUser2Nickname());
                map.put("photo",user.getPhoto());
            }
            friends.add(map);
        });
        Gson gson = new Gson();
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");

        PrintWriter writer = resp.getWriter();
        writer.print(gson.toJson(friends));
        writer.flush();
        writer.close();
    }
}
